package show.me.the.money.util.report;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.web.context.WebApplicationContext;

import show.me.the.money.config.reportSchema.ReportSchemaController;
import show.me.the.money.config.reportSchema.define.ReportSchema;
import show.me.the.money.dictionary.Dictionaries;
import show.me.the.money.dictionary.Dictionary;
import show.me.the.money.service.core.Service;
import show.me.the.money.util.context.Context;
import show.me.the.money.util.context.HashMapContext;

public class CompositeReportService implements Service {
	private static Log logger = LogFactory.getLog(CompositeReportService.class);

	public void execute(HashMap<String,Object> req,HashMap<String,Object> res,Context ctx){
		int code = 200;
		String msg = "Success";
		Context qCtx = new HashMapContext(req);
		ctx.putCtx("q", qCtx);
		HashMap<String,String> codeList=new HashMap<String, String>();
		
		if(!(req.get("manaUnitId") instanceof String)){
			return;
		}
		
		String manageUnit = (String)req.get("manaUnitId");
		if (StringUtils.isEmpty(manageUnit)) {
			code = 502;
			msg = "missing manaUnitId";
			logger.error("missing manaUnitId");
			return;
		}
		String id = (String)req.get("schema");
		ReportSchema reportSchema = ReportSchemaController.instance()
				.getSchemaDynamic(id, ctx);
		if (reportSchema != null) {
			try {
				List<HashMap> data = reportSchema.run(ctx);
				res.put("body", data);
				res.put("schema", reportSchema.json(ctx));
				res.put("totalCount", ctx.value("totalCount"));
				res.put("pageSize", ctx.value("pageSize"));
				res.put("pageNo", ctx.value("pageNo"));
				Dictionary dic = Dictionaries.instance().getDic(
						"manageUnitLevel");
				if (dic == null) {
					logger.error("dic[manageUnitLevel] not found");
				}

				String hql = "from STAT_Locate where manaUnitId like '"
						+ manageUnit
						+ "%' and (length(manaUnitId)="
						+ dic.getItem(String.valueOf(manageUnit.length()))
								.getProperty("level")
						+ " or length(manaUnitId)=" + manageUnit.length() + ")";
				data = this.executeSql(hql, ctx);
				for (HashMap r : data) {
					codeList.put((String)r.get("manaUnitId"), (String)r.get("mapSign"));
					if (r.get("manaUnitId").equals(manageUnit)
							&& r.containsKey("mapSign")) {
						res.put("mapSign", r.get("mapSign"));
					}
				}
				res.put("codeList", codeList);

			} catch (Exception e) {
				e.printStackTrace();
				code = 502;
				msg = "QueryFailed";
			}
		} else {
			code = 404;
			msg = "NoSuchSchema";
		}
		res.put(Service.RES_CODE, code);
		res.put(Service.RES_MESSAGE, msg);
	}
	
	private List executeSql(String hql, Context ctx){
		Session ss = null;
		List list = null;
		try {
			WebApplicationContext wac = (WebApplicationContext) ctx
					.get("_applicationContext");
			SessionFactory sf = (SessionFactory) wac
					.getBean("mySessionFactory");
			ss = sf.openSession();
			Query q = ss.createQuery(hql);
			list = q.list();
			Iterator tes = q.iterate();
		} catch (Exception e) {
			logger.error("executeSql error",e);
		} finally {
			if (ss != null && ss.isOpen())
				ss.close();
		}
		return list;
	}

}
